package client.comm.baoding.ui.vm

import android.app.Application
import android.net.Uri
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.comm.commlib.network.data.JsonResult
import client.comm.commlib.network.data.Ret
import client.comm.commlib.out_time
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.SharedUtil
import client.comm.commlib.utils.StoreUtil
import client.comm.commlib.utils.Util
import client.comm.baoding.api.bean.CurrentRechargeOrder
import client.comm.baoding.api.bean.UploadRet
import client.comm.baoding.api.bean.UserInfo
import client.comm.baoding.ui.viewmodel.MiddleVm
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Response

class PayOrderUpimgViewModel(app: Application) : MiddleVm(app) {
    val isShowing = MutableLiveData<Boolean>(false)
    val imgOne = MutableLiveData<Uri>()
    val userInfo = MutableLiveData<JsonResult<UserInfo>>()
    val callOne = MutableLiveData<JsonResult<CurrentRechargeOrder>>()
    val cancleRet = MutableLiveData<JsonResult<Ret>>()
    val okCall = MutableLiveData<JsonResult<Ret>>()
    val userRet = MutableLiveData<JsonResult<UserInfo>>()

    fun callUserInfo() {
        hold({
            server.userinfo().apply {
                body()?.let {
                    if (it.isSuccess) {
                        StoreUtil.saveBean(getApplication(), it.data as UserInfo)
                        SharedUtil.save("userState", it.data!!.status)
                    }
                }
            }
        }, success = {
            userInfo.value = it
        })
    }

    fun userInfo() {
        hold({
            server.userinfo().apply {
                body()?.let {
                    if (it.isSuccess) {
                        StoreUtil.saveBean(getApplication(), it.data!!)
                    }
                }
            }
        }, success = {
            userRet.value = it
        })
    }

    fun callRet() {
        hold({
            server.current_recharge()
        }, success = {
            callOne.value = it
        })
    }

    fun ok(owner: LifecycleOwner) {

        this@PayOrderUpimgViewModel.isShowing.value = true
        viewModelScope.launch {
            flow {
                var emm: Response<JsonResult<UploadRet>>? = null
                val file = Util.getLuBan(
                    owner,
                    this@PayOrderUpimgViewModel.imgOne.value!!
                )
                val requestFile: RequestBody = RequestBody.create(
                    "multipart/form-data".toMediaTypeOrNull(),
                    file
                )
                val body = MultipartBody.Part.createFormData(
                    "file",
                    file.name,
                    requestFile
                )
                val descriptionString = "file"
                val description = RequestBody.create(
                    "multipart/form-data".toMediaTypeOrNull(),
                    descriptionString
                )
                out_time {
                    val ret = server.upload(description, body)
                    emm = ret
                }
                emit(emm)
            }.map {
                var emm: Response<JsonResult<Ret>>? = null
                it?.body()?.let {
                    if (it.isSuccess) {
                        out_time {
                            val ret = server.upload_img(
                                it.data!!.url,
                                "${callOne.value!!.data!!.recharge_list[0].id}",
                                ""
                            )
                            emm = ret
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO).onCompletion { cause ->
                this@PayOrderUpimgViewModel.isShowing.value = false
            }.catch { cause ->
                if (cause != null) {
                    toast(cause.message)
                }
            }
                .collectLatest {
                    okCall.value = it?.body()
                }
        }
    }

    fun cancle() {
        this@PayOrderUpimgViewModel.isShowing.value = true
        hold({
            server.del_order("${callOne.value!!.data!!.recharge_list[0].id}")
        }, success = {
            cancleRet.value = it
        })
    }
}